<script setup>
import { forEach, merge } from 'lodash-es';
import { useRequest } from '@/hooks/requestHooks';
import { useWatch } from '@/hooks/useWatch';
import { useDownload } from '@/hooks/tool.js';
import { getBuildingReports } from '@/api/index.js';
import { basicLineYAxis } from '@/components/chart/options/baseOptions.js';
import AreaForm from '@/views/components/AreaForm.vue';
import DateChart from '@/views/components/DateChart.vue';
import { TableList } from '@/components/MainComponents.js';

const props = defineProps({
  type: { type: String, default: '' },
  unit: { type: String, default: '' },
});
const { type, unit } = toRefs(props);
const mColor = ['#4992ff', '#ee6666', '#eda422', '#5afe5d'];
const dColor = ['#4992ff', '#ee6666', '#5afe5d'];
const mDimensions = [
  'date',
  { name: 'thisValue', displayName: '实际能耗' },
  { name: 'same', displayName: '实际能耗趋势' },
  { name: 'togetherValue', displayName: '同比' },
  { name: 'chainValue', displayName: '环比' },
];
const dDimensions = [
  'date',
  { name: 'thisValue', displayName: '实际能耗' },
  { name: 'same', displayName: '实际能耗趋势' },
  { name: 'chainValue', displayName: '环比' },
];
const columnData1 = [
  {
    text: true,
    prop: 'date',
    label: '统计时间',
  },
  {
    text: true,
    prop: 'type',
    label: '能源名称',
  },
  {
    text: true,
    prop: 'thisValue',
    label: `实际能耗量（${unit.value}）`,
  },
  {
    text: true,
    prop: 'togetherValue',
    label: '同比（%）',
  },
  {
    text: true,
    prop: 'chainValue',
    label: '环比（%）',
  },
];
const columnData2 = [
  {
    text: true,
    prop: 'date',
    label: '统计时间',
  },
  {
    text: true,
    prop: 'type',
    label: '能源名称',
  },
  {
    text: true,
    prop: 'thisValue',
    label: `实际能耗量（${unit.value}）`,
  },
  {
    text: true,
    prop: 'chainValue',
    label: '环比（%）',
  },
];

const formParams = ref({});
const chartRef = ref(null);
const tableData = ref([]);
const pageObj = ref({
  pageNum: 1,
  pageSize: 10,
});
const chartOpts = ref({
  color: [],
  yAxis: [
    { name: `单位：${unit.value}` },
    merge({}, basicLineYAxis, {
      name: '单位：%',
      nameTextStyle: { align: 'right' },
    }),
  ],
  tooltip: {
    formatter: params => {
      if (Array.isArray(params) && params.length > 0) {
        params.splice(1, 1);
        let str = `<div class="u-mb5">${params[0].axisValue}</div>`;
        forEach(params, e => {
          let seriesName = e.seriesName;
          const value = e.value[e.dimensionNames[e.encode.y]] ?? '--';
          str += `<ul class="u-df-spb u-mb5"><li>${e.marker}${seriesName}</li><li class="u-ml30">${value}</li></ul>`;
        });
        return str;
      }
      return '';
    },
  },
  dataset: {
    dimensions: [],
    source: [],
  },
});
const columObj = ref({
  index: true,
  columnData: [],
});
const [res, loading, run] = useRequest(getBuildingReports, {
  defaultParams: [],
  manual: true,
  onSuccess: res => {
    let arr = forEach(res.data, n => {
      n.same = n.thisValue;
    });
    chartOpts.value.dataset.source = arr;
    tableData.value = res.data.slice(0, 10) ?? [];
    forEach(tableData.value, n => {
      n.type = type.value;
    });
    pageObj.value = {
      pageNum: 1,
      pageSize: 10,
    };
  },
});
const handleQuery = queryParams => {
  formParams.value = queryParams.buildingCode;
  const params = {
    energyType: type.value,
    enterpriseCode: queryParams.buildingCode.enterpriseCode,
    buildingCode: queryParams.buildingCode.buildingCode,
    dateType: chartRef.value?.dateParams.dateType,
    sDate: chartRef.value?.dateParams.startTime,
    eDate: chartRef.value?.dateParams.endTime,
  };
  run(params);
  chartOpts.value.dataset.dimensions = params.dateType === 'm' ? mDimensions : dDimensions;
  columObj.value.columnData = params.dateType === 'm' ? columnData1 : columnData2;
  chartOpts.value.color = params.dateType === 'm' ? mColor : dColor;
};
const handleChart = dateParams => {
  if (dateParams.startTime && dateParams.endTime) {
    const params = {
      energyType: '电',
      enterpriseCode: formParams.value.enterpriseCode,
      buildingCode: formParams.value.buildingCode,
      dateType: dateParams.dateType,
      sDate: dateParams.startTime,
      eDate: dateParams.endTime,
    };
    chartOpts.value.dataset.dimensions = params.dateType === 'm' ? mDimensions : dDimensions;
    columObj.value.columnData = params.dateType === 'm' ? columnData1 : columnData2;
    chartOpts.value.color = params.dateType === 'm' ? mColor : dColor;
    if (dateParams.dateType !== 'm') {
      chartOpts.value.tooltip.formatter = params => {
        if (Array.isArray(params) && params.length > 0) {
          params.splice(3, 1);
          params.splice(1, 1);
          let str = `<div class="u-mb5">${params[0].axisValue}</div>`;
          forEach(params, e => {
            let seriesName = e.seriesName;
            const value = e.value[e.dimensionNames[e.encode.y]] ?? '--';
            str += `<ul class="u-df-spb u-mb5"><li>${e.marker}${seriesName}</li><li class="u-ml30">${value}</li></ul>`;
          });
          return str;
        }
        return '';
      };
    } else {
      chartOpts.value.tooltip.formatter = params => {
        if (Array.isArray(params) && params.length > 0) {
          params.splice(1, 1);
          let str = `<div class="u-mb5">${params[0].axisValue}</div>`;
          forEach(params, e => {
            let seriesName = e.seriesName;
            const value = e.value[e.dimensionNames[e.encode.y]] ?? '--';
            str += `<ul class="u-df-spb u-mb5"><li>${e.marker}${seriesName}</li><li class="u-ml30">${value}</li></ul>`;
          });
          return str;
        }
        return '';
      };
    }

    run(params);
  }
};
const getList = e => {
  pageObj.value.pageNum = e.page;
  pageObj.value.pageSize = e.limit;
  tableData.value = res.value.slice((e.page - 1) * e.limit, e.page * e.limit);
  forEach(tableData.value, n => {
    n.type = type.value;
  });
};
const handleExport = () => {
  useDownload(
    '/energyservice/energy/getBuildingReportsExport',
    {
      energyType: type.value,
      enterpriseCode: formParams.value.enterpriseCode,
      buildingCode: formParams.value.buildingCode,
      dateType: chartRef.value?.dateParams.dateType,
      sDate: chartRef.value?.dateParams.startTime,
      eDate: chartRef.value?.dateParams.endTime,
    },
    `${type.value}能耗报表.xlsx`,
  );
};
useWatch(
  chartOpts,
  n => {
    n.series = Array.from({ length: n.dataset.dimensions.length - 1 }, (_, idx) => ({
      type: idx === 0 ? 'bar' : 'line',
      barWidth: 25,
      smooth: true,
      showSymbol: false,
      yAxisIndex: idx < 2 ? 0 : 1,
    }));
  },
  { deep: true },
);
</script>
<template>
  <div ref="appDom">
    <AreaForm ref="areaFormRef" projectType="JC" @handleQuery="handleQuery" />
    <DateChart
      ref="chartRef"
      v-loading="loading"
      class="u-p20 u-base-fg"
      style="height: 360px"
      :extraOpts="chartOpts"
      @handleDateParams="handleChart"
    />
    <div class="contBox">
      <div class="u-df-ed mb20">
        <el-button type="primary" plain size="small" @click="handleExport">导出报表</el-button>
      </div>
      <TableList
        v-loading="loading"
        :total="res?.length ?? 0"
        :tableData="tableData"
        :pageObj="pageObj"
        :columObj="columObj"
        @getList="getList"
      />
    </div>
  </div>
</template>
<style lang="scss" scoped></style>
